package com.example.lenovo.asia5b.my.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.SMSCode;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.example.lenovo.asia5b.util.StringUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.actitivy_password_modify_old_password;
import static com.wushi.lenovo.asia5b.R.id.btn_verify_code;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;


/**
 * Created by lenovo on 2017/8/30.
 */

public class UpdatePhoneActivity extends BaseActivity implements ICallBack {
    private String phone;
    private TimeCount timeCount;
    private long timeOut;
    private LoadingDalog loadingDalog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_phone);
        initView();
    }

    public void  initView(){
        F.id(R.id.public_title_name).text(getResources().getString(R.string.ghsj));
        F.id(public_btn_left).clicked(this);
        F.id(btn_verify_code).clicked(this);//获取验证码
        F.id(R.id.btn_verify_code_login).clicked(this);
        loadingDalog = new LoadingDalog(this);
        if (null != getUserBean()) {
            F.id(actitivy_password_modify_old_password).text(StringUtil.getMobilePhone(getUserBean().mobile_phone));
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case btn_verify_code://获取验证码
                phone = getUserBean().mobile_phone;
                if (TextUtils.isEmpty(F.id(R.id.actitivy_password_modify_new_password).getText().toString())){
                    U.Toast(this,getResources().getString(R.string.srxsjh));
                    return;
                }
                if(!TextUtils.isEmpty(phone)){
                    loadingDalog.show();
                    SMSCode.getCode(this,phone);
                    F.id(R.id.btn_verify_code).getView().setClickable(false);
                }else{
                    U.Toast(this,getResources().getString(R.string.srysjh)
                    );
                }
                break;
            case R.id.btn_verify_code_login:
                changesSaveData();
                break;
            default:
                break;
        }
    }

    public void changesSaveData() {
//        String jiu_phone = F.id(R.id.actitivy_password_modify_old_password).getText().toString();
        String jiu_phone = getUserBean().mobile_phone;
        String xin_phoen = F.id(R.id.actitivy_password_modify_new_password).getText().toString();
        String code = F.id(R.id.activity_login_phone_code).getText().toString();
        if (TextUtils.isEmpty(jiu_phone)) {
            U.Toast(this,getResources().getString(R.string.srysjh));
        } else if (TextUtils.isEmpty(xin_phoen)) {
            U.Toast(this,getResources().getString(R.string.srxsjh));
        } else if (TextUtils.isEmpty(code)){
            U.Toast(this,getResources().getString(R.string.yzmbnwk));
        } else if (TextUtils.equals(jiu_phone,xin_phoen)){
            U.Toast(this,getResources().getString(R.string.sjmhycz));
        }
        else{
            loadingDalog.show();
            try {
                Map<String, String> parmaMap = new HashMap<String, String>();
                String url = Setting.UPDATE_PHONE;
                String user_id = getUserBean().user_id;
                Date date = new Date();
                String time = String.valueOf(date.getTime());
                String[] sort = {"user_id"+user_id,"code"+code,"new_phone"+xin_phoen,"time"+time};
                String sortStr = Logic.sortToString(sort);
                String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
                parmaMap.put("user_id", user_id);
                parmaMap.put("code",""+code);
                parmaMap.put("new_phone",""+xin_phoen);
                parmaMap.put("time",time);
                parmaMap.put("sign",md5_32);
                JsonTools.getJsonAll(this, url, parmaMap, 1);
            }catch (Exception e) {

            }
        }
    }
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            try{
                if(result != null && result instanceof JSONObject){
                    if(action == 0){
                        JSONObject jsonObject = (JSONObject)result;
                        String msgText = jsonObject.getString("MsgText");
                        if("true".equals(msgText)){
                            timeCount = new TimeCount(60000, 1000);
                            timeCount.start();
                        }else if("false".equals(msgText)){
                            String state = jsonObject.getString("State");
                            U.Toast(UpdatePhoneActivity.this,state);
                        }
                        loadingDalog.dismiss();
                    }else if(action == 1){
                        JSONObject jsonObject = (JSONObject)result;
                        int state = jsonObject.getInt("State");
                        if(state == 0){
                            UserBean bean2 = getUserBean();
                            bean2.mobile_phone =  F.id(R.id.actitivy_password_modify_new_password).getText().toString();
                            SharedPreferencesUtils.setObjectToShare(bean2,"user");
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.modify_succeed));
                            finish();
                        }else if(state == 1){
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.wdl));
                        }else if(state == 4){
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.sjyzmcw));
                        }else if(state == 5){
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.sjmhycz));
                        }else if(state == 6){
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.modify_defeated));
                        } else if(state == 15){
                            U.Toast(UpdatePhoneActivity.this,getResources().getString(R.string.yzmsx));
                        }
                        loadingDalog.dismiss();
                    }
                }
            }catch (Exception e){
                Log.e("短信JSONError:d",e.getMessage());
            }
        }
    };


    @Override
    public void logicFinish(Object result, int action){
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 获取验证码倒计时
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            F.id(R.id.btn_verify_code).getView().setClickable(false);
            timeOut = millisUntilFinished / 1000;
            F.id(R.id.btn_verify_code).text(getResources().getString(R.string.message_has_been_sent)+"(" + timeOut + ")");
        }

        @Override
        public void onFinish() {
            F.id(R.id.btn_verify_code).text(getResources().getString(R.string.to_obtain_the_verification_code));
            F.id(R.id.btn_verify_code).getView().setClickable(true);
        }
    }
}
